const WATERMARK_ID = '__global_watermark__'

const defaultOptions = {
  width: 360,
  height: 240,
  fontSize: 16,
  fontWeight: 400,
  fontFamily: 'PingFang SC, Microsoft YaHei, sans-serif',
  color: 'rgba(0, 0, 0, 0.08)',
  rotate: -20
}

let currentText = ''
let currentOptions = { ...defaultOptions }
let observer = null

const canUseDom = () => typeof window !== 'undefined' && typeof document !== 'undefined'

const ensureContainer = () => {
  if (!canUseDom()) return null
  let container = document.getElementById(WATERMARK_ID)
  if (!container) {
    container = document.createElement('div')
    container.id = WATERMARK_ID
    document.body.appendChild(container)
  }
  Object.assign(container.style, {
    position: 'fixed',
    top: '0',
    left: '0',
    width: '100%',
    height: '100%',
    zIndex: '2000',
    pointerEvents: 'none',
    backgroundRepeat: 'repeat',
    backgroundPosition: '0 0'
  })
  return container
}

const bindObserver = () => {
  if (!canUseDom()) return
  if (observer) {
    observer.disconnect()
  }
  observer = new MutationObserver(() => {
    const existing = document.getElementById(WATERMARK_ID)
    if (!existing && currentText) {
      renderWatermark()
    }
  })
  observer.observe(document.body, { childList: true })
}

const renderWatermark = () => {
  if (!canUseDom() || !currentText) return
  const container = ensureContainer()
  if (!container) return

  const { width, height, rotate, fontSize, fontWeight, fontFamily, color } = currentOptions
  const canvas = document.createElement('canvas')
  const ratio = window.devicePixelRatio || 1
  canvas.width = width * ratio
  canvas.height = height * ratio
  const ctx = canvas.getContext('2d')
  if (!ctx) return

  ctx.scale(ratio, ratio)
  ctx.clearRect(0, 0, width, height)
  ctx.translate(width / 2, height / 2)
  ctx.rotate((Math.PI / 180) * rotate)
  ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`
  ctx.fillStyle = color
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'
  ctx.fillText(currentText, 0, 0)

  container.style.backgroundImage = `url(${canvas.toDataURL('image/png')})`
  container.style.backgroundSize = `${width}px ${height}px`
  bindObserver()
}

export const setWatermark = (text, options = {}) => {
  currentText = text
  currentOptions = { ...defaultOptions, ...options }
  if (!text) {
    clearWatermark()
    return
  }
  renderWatermark()
}

export const refreshWatermark = () => {
  renderWatermark()
}

export const clearWatermark = () => {
  if (observer) {
    observer.disconnect()
    observer = null
  }
  if (!canUseDom()) return
  const container = document.getElementById(WATERMARK_ID)
  if (container && container.parentNode) {
    container.parentNode.removeChild(container)
  }
}
